/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package vn.edu.vttu;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeBodyPart;
import javax.swing.JOptionPane;

/**
 *
 * @author Lucas Nguyen
 */
public class getFile {
    
    //    private static final String HOST = "nhom5.no-ip.org";
  //private static final String USERNAME = "sinhvien1@nhom5.no-ip.org";
 // private static final String PASSWORD = "1";
  
    
         public static void getFileOfMail( int i) {
    //  Folder folder = null;
      // Store store = null;
         try {
          Properties properties = System.getProperties();
            Session session = Session.getDefaultInstance(properties);
            Store store = session.getStore("pop3");
            store.connect(ConnectionServer.mailHost, ConnectionServer.kiemTraDiaChiGmail(ConnectionServer.userName),ConnectionServer.passWord);
            Folder folder = store.getFolder("inbox");
             if (!folder.exists()) {
            System.out.println("Không có hợp thư đến...");
            System.exit(0);
                           } 
             folder.open(Folder.READ_WRITE);
        Message[] messages = folder.getMessages();
         System.out.println("Bắt đầu kết nối................"); 
               System.out.println("No of Messages : " + folder.getMessageCount());
         System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount()); 
   //    for (int i=0; i < messages.length; ++i) {
       //  int i=1;
       
        Message msg = messages[i];
       /* String from = "unknown";
        if (msg.getReplyTo().length >= 1) {
          from = msg.getReplyTo()[0].toString();
        }
        else if (msg.getFrom().length >= 1) {
          from = msg.getFrom()[0].toString();
        }
        String subject = msg.getSubject();
        String file = msg.getFileName();
        System.out.println("Saving ... " + subject +" ---" + from);*/
              String filename = "c:/temp/" +i;
             saveParts(msg.getContent(), filename);
               
            folder.close(true);
        store.close(); 
         } 
         catch(Exception e) {
            e.printStackTrace();
               JOptionPane.showConfirmDialog(null, "Không thế kết nối Server...!","Lỗi",JOptionPane.YES_OPTION,JOptionPane.WARNING_MESSAGE);
         }
         
     }//php3doi
    
    
    /*--hàm lấy file-- truyền vào tham số là conten và tên file*/
       public static void saveParts(Object content, String filename)throws IOException, MessagingException
  {
    OutputStream out = null;
    InputStream in = null;
    try {
      if (content instanceof Multipart) {
        Multipart multi = ((Multipart)content);
        int parts = multi.getCount();
        for (int j=0; j < parts; ++j) {
          MimeBodyPart part = (MimeBodyPart)multi.getBodyPart(j);
          if (part.getContent() instanceof Multipart) {
            // part-within-a-part, do some recursion...
            saveParts(part.getContent(), filename);
          }
          else {
            String extension = "";
            if (part.isMimeType("text/html")) {
             // extension = "html";
            }
            else {
              if (part.isMimeType("text/plain")) {
               // extension = "txt";
              }
              else {
                //  Try to get the name of the attachment
                extension = part.getDataHandler().getName();
              }
              filename = filename  + extension;// ghi tên file của file tải về
              System.out.println("... " + filename);
              out = new FileOutputStream(new File(filename));
              in = part.getInputStream();
              int k;
              while ((k = in.read()) != -1) {
                out.write(k);
              }// ghi file
            }
          }
        }
      }
    }
    finally {
      if (in != null) { in.close(); }
      if (out != null) { out.flush(); out.close(); }
    }
  }
      
}
